import {configureStore,createSlice} from "@reduxjs/toolkit";
import goods from "./slice/goods";
import cart from "./slice/cart";
// 商品模块
const goodsSlice = createSlice({
    name:"goods",
    initialState:{
        goodsList:[]
    },
    reducers:{
        // 添加商品
        addGoods(state,{payload}){
            state.goodsList.unshift({
                id:Math.random().toString(36).slice(2),
                ...payload
            })
        }
    }
})

// const goods = goodsSlice.reducer;
// 购物车模块
const cartSlice = createSlice({
    name:"cart",
    initialState:{
        cartList:[],
    },
    reducers:{
        joinCart(state,{payload}){
            /*思路：
            * 1- payload是商品信息，根据payload.id去购物车中查找是否有相同的元素
            *    1-1：有：buyNum+=1
            *    1=2：无:为cartList增加一个元素*/
           const info = state.cartList.find(v=>v.id ===payload.id);
           if(info){
            // 有
            info.buyNum+=1;
           }else{
            // 无
            state.cartList.unshift({
                ...payload,
                buyNum:1
            })
           }
        }
    }
})
// const cart = cartSlice.reducer;
const store = configureStore({
    reducer:{
        goods,
        cart
    }
})
export const {addGoods} = goodsSlice.actions;
export const {joinCart} = cartSlice.actions;
export default store;